import {Component, ElementRef, Input, Output, EventEmitter, OnInit, ViewChild, Injectable} from '@angular/core';
import {FileUploadNormalService} from "./file-upload-normal.service";
import {environment} from '../../../../../environments/environment';
import {Util} from "../../../../common/util";
import * as _ from 'lodash'
import {FileUploader} from 'ng2-file-upload';


/**
 * 网下新股发起询价
 */
@Component({
  selector: 'new-stock-purchase-file-upload-normal',
  templateUrl: './file-upload-normal.component.html',
  styleUrls: ['./file-upload-normal.component.scss'],
  providers: [FileUploadNormalService]
})
export class FileUploadNormalComponent implements OnInit {

  @Input()
  /**
   * [modalConfig 配置参数]
   * @type {
        modalTile: "", // modal title
        title: "", // titel
        url: "", // url
        method: "", // POST OR GET
        itemAlias: "", // file alias
        formDatas: [] // POST 参数
      };
   */
  public modalConfig: any;

  @Output()
  close: EventEmitter<boolean> = new EventEmitter<boolean>();

  // 上传成功，用于标记是否刷新上层调用
  public hasUploadSucc = false;

  // 上传的文件名称
  public fileName: string;

  public modalStatus: boolean;

  public uploader: FileUploader = new FileUploader({});


  // 定义事件，选择文件
  selectedFileOnChanged(event: any) {
    // 打印文件选择名称(带路径)
    // console.log(event.target.value);
    this.fileName = event.target.value;
  }

  // 定义事件，上传文件
  uploadFile() {
    const that = this;

    const fileItem = _.last(this.uploader.queue); // 上传最后一个选择的文件

    fileItem.url = this.modalConfig.url;
    fileItem.method = this.modalConfig.method;
    fileItem.alias = this.modalConfig.itemAlias;
    // 为了测试，上线要去掉
    fileItem.headers = [{name: 'token', value: sessionStorage.getItem('username')}];

    // 添加 POST 其他参数
    this.uploader.onBuildItemForm = (item, form) => {
      if (this.modalConfig.formDatas) {
        _.forEach(this.modalConfig.formDatas, item => {
          form.append(item.key, item.value);
        });
      }
      // 文件名称   TODO: 待优化
      if (form["filename"]) {
        form["filename"] = fileItem.file.name; // 文件名称
      } else {
        form.append('filename', fileItem.file.name); // 文件名称
      }
    };
    // 上传
    fileItem.onSuccess = function (response, status, headers) {
      const retVal = JSON.parse(response);
      if (retVal.code  === 0) {
        var str = "";
        for(let i in retVal.data){
          if(retVal.data[i]!=""){
            if(i == "fundErr"){
              retVal.data[i] = retVal.data[i].replace(/；/g,"<br>");
            }
            str += retVal.data[i] + "<br>"
          }
        }
        // 上传文件后获取服务器返回的数据
          window["swal"]({
            title: `${retVal.msg}`,
            text: `<div style="font-size:13px">${str}</div>`,
            html: true,
            type: "success"
          });
        // 上传成功
        that.hasUploadSucc = true;
        that.closeModal();
      } else if (retVal.code  === 1001) {
        // 特殊处理： 导入的入围文件没有询价，则从新调用该接口
        fileItem.url = environment.server + "otc/v1/Newstock/RW";

        window["swal"]({
            title: "提示",
            text: "导入的入围文件有基金未发起询价，是否继续导入?",
            type: "info",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            closeOnCancel: true,
            showLoaderOnConfirm: true
          },
          function (isConfirm) {
            if (isConfirm) { // 确认
              fileItem.upload(); // 开始上传
            } else { // 取消
              // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
            }
          });

      } else if (retVal.code  === 1002) {
        // 特殊处理： 导入的中签文件没有询价，则从新调用该接口
        fileItem.url = environment.server + "otc/v1/Newstock/ZQ";

        window["swal"]({
            title: "提示",
            text: "导入的中签件有基金未发起询价，是否继续导入?",
            type: "info",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            closeOnCancel: true,
            showLoaderOnConfirm: true
          },
          function (isConfirm) {
            if (isConfirm) { // 确认
              fileItem.upload(); // 开始上传
            } else { // 取消
              // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
            }
          });

      } else {
        // 上传文件后获取服务器返回的数据错误
        window["swal"]("导入失败", retVal.detailMsg, "error");
      }
    };

    fileItem.upload(); // 开始上传
  }

  @ViewChild("modal")
  public modal: ElementRef;

  @ViewChild("fileInput")
  public fileInput: ElementRef;

  constructor(public fileUploadNormalService: FileUploadNormalService) {

  }

  ngOnInit() {
  }

  public openModal(): void {
    this.modalStatus = true;
    Util.$(this.modal.nativeElement).modal('show');
  }

  public closeModal(): void {
    // 关闭重置信息
    // this.modalConfig = "";
    // this.fileName = "";
    this.close.emit(this.hasUploadSucc); // 关闭后触发上层刷新事件
    this.modalStatus = false;
    this.clearFileQueue();

    Util.$(this.modal.nativeElement).modal('hide');
  }

  public toggleModal(): void {
    this.modalStatus = !this.modalStatus;
    Util.$(this.modal.nativeElement).modal('toggle');
  }

  public clearFileQueue() {
    this.fileInput.nativeElement.value=null;
    this.uploader.clearQueue();
  }
}
